package resolver

import (
	"file-comparison-go/utils"
	"fmt"
	"io/ioutil"
	"path/filepath"
	"strconv"
	"strings"
)

type MergeResolve struct {
	path    string
	isNoDir bool
	isZip   bool
	isJar   bool
	*ComparisonResolver
}

func NewMergeResolve(path string, isNoDir, isZip, isJar bool) *MergeResolve {
	path, _ = filepath.Abs(path)
	return &MergeResolve{path: path, ComparisonResolver: &ComparisonResolver{FileMap: make(map[string]*FileInfo)}, isNoDir: isNoDir, isZip: isZip, isJar: isJar}
}

func (mr *MergeResolve) Resolve() (*ComparisonResolver, error) {
	readedBytes, err := ioutil.ReadFile(mr.path)
	if err != nil {
		fmt.Println(err)
		return nil, err
	}
	threeDs := utils.New3DS()
	readedBytes = threeDs.Decode(readedBytes)
	results := strings.Split(string(readedBytes), "\n")
	metaInfo := strings.Split(results[0], Split)
	mr.RootPath = metaInfo[1]
	if metaInfo[0] == "1" {
		mr.FileType = DIR
	} else {
		mr.FileType = FILE
	}

	for _, line := range results[1:] {
		arr := strings.Split(line, Split)
		if len(arr) >= 3 {
			var isDir bool
			if arr[2] == "1" {
				isDir = true
			}
			size, _ := strconv.Atoi(arr[3])
			fi := NewFileInfo(arr[0], arr[1], isDir, int64(size), Sha512)
			if len(arr) >= 4 {
				fi.Hash = arr[4]
			}
			if strings.Contains(fi.Path, ".jar!\\") || strings.Contains(fi.Path, ".zip!\\") || strings.Contains(fi.Path, ".tar.gz!\\") || strings.Contains(fi.Path, ".tar!\\") {
				if (mr.isJar && strings.Contains(fi.Path, ".jar!\\")) || mr.isZip {
					if !mr.isNoDir {
						mr.FileMap[fi.Path] = fi
					}
				}
				mr.Files = append(mr.Files, fi)
			} else {
				if !mr.isNoDir {
					mr.FileMap[fi.Path] = fi
				}
				mr.Files = append(mr.Files, fi)
			}
		}
	}

	return mr.ComparisonResolver, nil
}
